<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DNA Modeling Game</title>
<script src="three.js"></script>
<script src="helvetiker.js"></script>
<script src="makeObjects.js"></script>
<script src="jquery-2.0.3.min.js"></script>
 <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
 <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script type="text/javascript">



    var camera, scene, renderer;
    var atcg;
    var pointerDetectRay, projector, mouse2D;
    var dragged = false;
    var draggedObject;
    var overObject;

    var positions;

    var lastMouseX = -1;
    var lastMouseY = -1;

    var letters = [ 'A', 'T', 'C', 'G' ];

    //POSITIONS
    var ATCG_POS_X = -430;
    var ATCG_POS_Y = -200;

    var PAS_POS_X = 50;
    var PAS_POS_Y = 0;

    var PAS2_POS_X = 280;
    var PAS2_POS_Y = 0;

    var CHAIN_POS_X = 550;
    var CHAIN_POS_Y = -100;

    var WELCOME_POS_X = -300;
    var WELCOME_POS_Y = 0;

    function init() {

        camera = new THREE.PerspectiveCamera(75, window.innerWidth
                / window.innerHeight, 1, 10000);
        camera.position.z = 1000;

        scene = new THREE.Scene();

        makeAtcgBar();
        makeDNAChain();
        makeDNAPas();
        makeDNAPas2();
        //makeWelcomePage();
        //makeFinalMessage();

        renderer = new THREE.WebGLRenderer({
            antialiasing : true
        });

        renderer.setSize(window.innerWidth, window.innerHeight - 100);
        renderer.domElement.style.position = 'absolute';
        renderer.domElement.style.top = '100px';

        renderer.setClearColorHex(0xCCCCCC, 1.0);
        renderer.clear();

        document.body.appendChild(renderer.domElement);
        //$(renderer.domElement).css("top", "500px");
        //$(renderer.domElement).css("top", "200px");

        //renderer.domElement.add

        pointerDetectRay = new THREE.Raycaster();
        pointerDetectRay.ray.direction.set(0, -1, 0);
        projector = new THREE.Projector();
        mouse2D = new THREE.Vector3(0, 0, 0);

        //document.addEventListener("click", mouseClick);
        document.addEventListener("mousemove", mouseMove);
        document.addEventListener("mousedown", mouseDown);
        document.addEventListener("mouseup", mouseUp);

    }

    function restart(){
        camera = new THREE.PerspectiveCamera(75, window.innerWidth
                / window.innerHeight, 1, 10000);
        camera.position.z = 1000;

        scene = new THREE.Scene();

        makeAtcgBar();
        makeDNAChain();
        makeDNAPas();
        makeDNAPas2();
        //makeWelcomePage();
        //makeFinalMessage();

        renderer = new THREE.WebGLRenderer({
            antialiasing : true
        });

        renderer.setSize(window.innerWidth, window.innerHeight - 100);


        renderer.setClearColorHex(0xCCCCCC, 1.0);
        renderer.clear();

        //document.body.appendChild(renderer.domElement);
        //$(renderer.domElement).css("top", "500px");
        $(renderer.domElement).css("top", "200px");

        //renderer.domElement.add

        pointerDetectRay = new THREE.Raycaster();
        pointerDetectRay.ray.direction.set(0, -1, 0);
        projector = new THREE.Projector();
        mouse2D = new THREE.Vector3(0, 0, 0);

        //document.addEventListener("click", mouseClick);
        document.addEventListener("mousemove", mouseMove);
        document.addEventListener("mousedown", mouseDown);
        document.addEventListener("mouseup", mouseUp);
    }

function makeWelcomePage() {

        var welcome = new THREE.Object3D();

        //plane
        var cubesPlaneGeometry = new THREE.PlaneGeometry(800, 500, 1, 0);
        var cubesPlaneMaterial = new THREE.MeshBasicMaterial({
            color : Math.random()*0x0000ff,
            wireframe : false
        });

        textMaterial = new THREE.MeshBasicMaterial({
            color : 0x0000ff,
            wireframe : false
        });

        positions = new Array();

            var textGeo = new THREE.TextGeometry("Welcome", {
                size : 100,
                height : 20,
                face : "helvetiker"
            });
            textGeo.computeBoundingBox();

            var textMesh = new THREE.Mesh(textGeo, textMaterial.clone());
            textMesh.position.x = -40;
            textMesh.position.y = -40;



            //node for cube & mesh
            var node = new THREE.Object3D();
            node.add(textMesh);

            node.position.x = 10;
            node.position.y = 20;

            //positions[i] = new THREE.Vector3(node.position.x, node.position.y, 0);

            welcome.add(node); //adding to welcome



        welcome.position.x =WELCOME_POS_X;
        welcome.position.y = WELCOME_POS_Y;
        welcome.position.z = 100;

        scene.add(welcome); //adding welcome to the scene
    }

    //var spheres = Array[100];

    //var dnachain;





    var animatedCubes = 0; //pocet vytvorenych kostek
    var finishedCubes = 0; //pocet padajicich

    var removeCube = null; //cube to be removed
    var removeTime = 0;

    var time;

    function animate(t){

        if(removeCube != null && removeTime <= t){
            scene.__removeObject(removeCube);
            removeCube = null;
        }

        if( t > animatedCubes * 1000 + 500 ){
            animatedCubes++;
        }

        for(var i = finishedCubes +1; i<= Math.min(animatedCubes, ncubes); i++){
            pas2.children[i].position.y -= 3;
        }

        var j = Math.min(finishedCubes +1, ncubes);
        if(pas2.children[j].position.y <= j* 200 - 600){
            finishedCubes++;
        }

        //animation of dragged object
        if (dragged) {
            draggedObject.position.z = Math.sin(t * 0.005) * 40 + 20;
        } else if(overObject != null){
            //overObject.children[0].material.color.setHex(0x0000aa);
            //overObject.children[1].material.color.setHex(0x0000aa);
        }

        if(movingObject != null){
            if(movingObject.position.distanceTo(desiredPosition) > 5){

            }
        }

        if(completed){
            cubes = pas2.children;
            for(var i = 0; i< ncubes; i++){
                    cubes[i+1].position.y += Math.sin(t * 0.005) * 2;
                    cubes2[i].position.y += Math.sin(t * 0.005) * 2;
                    cubes[i+1].children[0].material.color.setHex(0x00ffff);
                    cubes2[i].children[0].material.color.setHex(0x00ffff);
            }



        }

        dnachain.rotateY(0.01);

        pointerDetectRay = projector.pickingRay(mouse2D.clone(), camera);

        timer = t * 0.3 ;

        requestAnimationFrame(animate);
        //textCubeNode.position.y = Math.cos(timer)*Math.cos(timer) * 10;

        //atcg.rotation.x +=  0.02;
        //atcg.rotation.y +=  0.03;
        //textCubeNode.rotation.y =  0.2;

        renderer.render(scene, camera);
        //window.requestAnimationFrame(animate, renderer.domElement);

    }

    var ncubes = Math.floor(Math.random()*4 + 3); //number of cubes
    var hotkostka=0;
    var completed=false;
    var cubes2 = new Array(ncubes);

    function mouseUp(event){

        dragged = false;
        draggedObject.position.z = 0;
        //move(draggedObject, positions[0]);

        var cubes = pas2.children;

        var min = 9999999; //vzdalenost k nejblizsi
        var nearest;
        var nearestObject;

        for (var i = 1; i < ncubes+1; i++) {
            var pos = cubes[i].position.clone();
            pos.add(pas2.position);
            pos.x -= 200;

            var dist = draggedObject.position.distanceTo(pos);

            if (dist < min) {
                min = dist;
                nearest = pos;
                nearestObject = cubes[i];
            }
        }

        if (draggedObject.position.distanceTo(nearest) < 200 && finishedCubes >= ncubes) {

            var letterA = getLetter(draggedObject);
            var letterB = getLetter(nearestObject);

            if((letterA == 'A' && letterB == 'T') || (letterA == 'T' && letterB == 'A') ||
                    (letterA == 'C' && letterB == 'G') || (letterA == 'G' && letterB == 'C')){
                draggedObject.position = nearest;
				
				nearestObject.children[1].material.color = draggedObject.color;
        		
				
				
                cubes2[hotkostka] = draggedObject;
                hotkostka++;

                //var x = draggedObject.position.x + 100;
                //var y = draggedObject.position.y;

                var n = 3;

                if(letterA == 'A' || letterA == 'T'){
                    n = 2;
                }

                createHydroConnection(draggedObject, 0, 0, n);

                if(hotkostka==ncubes){
                    completed=true;
                }
            } else {
                draggedObject.children[0].material.color.setHex(0xff00ff);
                if(removeCube != null){
                    scene.__removeObject(removeCube);
                }
                removeCube = draggedObject;
                removeTime = time + 1000;


            }

            //document.title = 'dragged: ' + letterA + ', nearest: ' + letterB;
        }
        else{
            // TODO
            // tady doplnte co se ma stat s pismenama, ktere uzivatel pusti vpravo
            draggedObject.children[0].material.color.setHex(0xff0000);
            if(removeCube != null){
                scene.__removeObject(removeCube);
            }
            removeCube = draggedObject;
            removeTime = time + 1000;
        }

        draggedObject = null;


    }


    function mouseDown(event){
		if(completed  ){
					location.replace("../2/game2.html");
					return;
				}
	
	
     event.preventDefault();
            mouse2D.x = (event.clientX / window.innerWidth) * 2 - 1;
            mouse2D.y = -(event.clientY / window.innerHeight) * 2 + 1;

            var intersects = pointerDetectRay.intersectObjects(atcg.children, true);
            if (intersects.length > 0 && intersects[0].object != atcg.children[0]) {
				//&& intersects[0].object.parent.parent == pas2.children[0]
			
                //draggedObject = intersects[0].object.parent;
                var obj = intersects[0].object.parent;
                //draggedObject = new THREE.Object3D();

                //draggedObject.add(obj.children[0].clone());
                //draggedObject.add(obj.children[1].clone());
                var color = obj.children[1].material.color; //0x5555ff;
                draggedObject = makeCube2(getLetter(obj), scene, color, obj.position.x + ATCG_POS_X, obj.position.y + ATCG_POS_Y);

                //draggedObject.position = obj.position.clone();
                //draggedObject.position.x +=ATCG_POS_X;
                //draggedObject.position.y +=ATCG_POS_Y;


                //scene.add(draggedObject);

                lastMouseX = -1;
                lastMouseY = -1;
                dragged = true;
        }
    }




    //mouseMove
    function mouseMove(event){
		
	
	
	
        mouse2D.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse2D.y = -(event.clientY / window.innerHeight) * 2 + 1;

        var q = 200;
        if (dragged) {

            var dX = 0;
            var dY = 0;

            if (lastMouseX == -1 && lastMouseY == -1) {
                lastMouseX = mouse2D.x;
                lastMouseY = mouse2D.y;
            }

            dX = mouse2D.x - lastMouseX;
            dY = mouse2D.y - lastMouseY;

            draggedObject.position.x += dX * window.innerWidth;
            draggedObject.position.y += dY * window.innerHeight;

            lastMouseX = mouse2D.x;
            lastMouseY = mouse2D.y;
        } else {
            var intersects = pointerDetectRay.intersectObjects(
                    atcg.children, true);
            if (intersects.length > 0 && intersects[0].object != atcg.children[0]) {
                overObject = intersects[0].object.parent;
            } else {
                //overObject.children[0].material.color.setHex(0x0000ff);
                //overObject.children[1].material.color.setHex(0x0000ff);
                overObject = null;
            }
        }
    }


    function getLetter(object){
        return object.children[0].geometry.text;
    }

    var movingObject;
    var desiredPosition;

    //move - moving specified object to desired position
    function move(object, target){
        movingObject = object;
        desiredPosition = target;
        object.position = target.clone();
    }



    function webgl_detect(return_context)
{
    if (!!window.WebGLRenderingContext) {
        var canvas = document.createElement("canvas"),
             names = ["webgl", "experimental-webgl", "moz-webgl", "webkit-3d"],
           context = false;

        for(var i=0;i<4;i++) {
            try {
                context = canvas.getContext(names[i]);
                if (context && typeof context.getParameter == "function") {
                    // WebGL is enabled
                    if (return_context) {
                        // return WebGL object if the function's argument is present
                        return {name:names[i], gl:context};
                    }
                    // else, return just true
                    return true;
                }
            } catch(e) {}
        }

        // WebGL is supported, but disabled
        document.write("WebGL is supported, but disabled <br/> Find out how to get it <a href='http://blog.teamtreehouse.com/the-beginners-guide-to-three-js#BrowserCompatibility' style='color:#000'>here</a>");
        return false;
    }

    // WebGL not supported
    document.write("Your browser does not seem to support <a href='http://khronos.org/webgl/wiki/Getting_a_WebGL_Implementation' style='color:#000'>WebGL</a>.<br/> Find out how to get it <a href='http://blog.teamtreehouse.com/the-beginners-guide-to-three-js#BrowserCompatibility' style='color:#000'>here</a>");
    return false;
}


    $(function() {
        $( "input[type=submit], a, button" )
        .button()
        .click(function( event ) {
        event.preventDefault();
        });
    });

    $(function() {
        //$( "#dialog" ).dialog();
    });


</script>

<style>

</style>
</head>
<body>



    <script>
    if (webgl_detect()) {
        init();
        animate(new Date().getTime());
    }


    </script>

<!--<button onClick="init();">Nová hra</button>-->
</br><button onClick="location.reload(false);">Quick Restart</button>
<button onClick="location.href = 'http://www.fbmi.cvut.cz';">End Game</button>
<button onClick="location.href = 'welcome.html';">New Game</button>
<button onClick="$( '#dialog' ).dialog();">How to play?</button>


<div id="dialog" title="Pravidla" style="display:none;">
<p>DNA je biologická makromolekula 
– polymer v podobě řetězce,dvoušroubovice.
Nukleotidy jsou vždy složeny z cukrudeoxyribózy,
 fosfátové skupiny a jedné ze čtyř nukleových bází.
 Informační funkci mají právě báze,
 jimiž může být adenin(A), guanin (G), cytosin (C) nebo thymin (T).
 První dvě patří mezi puriny, zbylé mezi tzv. pyrimidiny
 Spojute jednotlivé baze podle pravidla komplimentarity A-T, C-G
 A se páruje s T (vzájemně jsou spojeny dvěma vodíkovými vazbami)
G se páruje s C (vzájemně jsou spojeny třemi vodíkovými vazbami)
</p>
</div>

</body>
</html>
